//
//  LMHomeViewController.m
//  李明微博
//
//  Created by apple on 15/12/4.
//  Copyright (c) 2015年 李明. All rights reserved.
//

#import "LMHomeViewController.h"
#import "UIBarButtonItem+Item.h"

#import "LMTitleButton.h"
#import "LMPopMenu.h"
#import "LMCover.h"
#import "LMOneViewController.h"


//处理数据变对象
#import "MJExtension.h"



#import "LMAccountTool.h"

#import "LMAccount.h"

#import "CZStatus.h"
#import "CZPhoto.h"
#import "CZUser.h"
#import "UIImageView+WebCache.h"

//处理刷新的
#import "MJRefresh.h"

#import "LMStatusTool.h"

#import "LMUserTool.h"
#import "LMStatusCell.h"

#import "LMStatusFrame.h"




@interface LMHomeViewController ()<LMCoverDelegate>

@property (nonatomic,weak) LMTitleButton *titleButton;
@property (nonatomic,strong) LMOneViewController *one;


/*ViewModel:CZStatusFrame*/
@property (nonatomic,strong)NSMutableArray<LMStatusFrame *> *statusFrames;

@end

@implementation LMHomeViewController



-(NSMutableArray *)statusFrames
{
    if (_statusFrames == nil) {
        _statusFrames = [NSMutableArray array];
    }
    return _statusFrames;
}
- (LMOneViewController *)one
{
    if (_one==nil) {
        _one = [[LMOneViewController alloc] init];
    }
    
    return _one;
}

- (void)refresh
{
    [self.tableView.mj_header beginRefreshing];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpNavgationBar];
    
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(showdateDown)];
    [self.tableView.mj_header beginRefreshing];
    
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(showdateUp)];
    
    
    [LMUserTool userInfoWithSuccess:^(CZUser *user) {
        
        
        [self.titleButton setTitle:user.name forState:UIControlStateNormal];
        
        LMAccount *account = [LMAccountTool account];
        account.name = user.name;
        
        [LMAccountTool saveAccount:account];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}





- (void)setUpNavgationBar
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_friendsearch"] highImage:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"] target:self action:@selector(friendsearch) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_pop"] highImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    
    LMTitleButton *titleButton = [LMTitleButton buttonWithType:UIButtonTypeCustom];
    _titleButton = titleButton;
    
    NSString *title = [LMAccountTool account].name?:@"首页";
    NSLog(@"%@",title);
    
    [titleButton setTitle:title forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateSelected];
    
    titleButton.adjustsImageWhenDisabled = NO;
    
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleButton;
    
}


- (void)showdateDown
{
    
    
    NSString *since_id = nil;
    
    if (self.statusFrames.count) {
        
        
        CZStatus *s = [self.statusFrames[0] status];
        since_id=s.idstr;
    }
    
    
    [LMStatusTool newStatusWithSinceId:since_id success:^(NSArray *statuses) {
        
        [self.tableView.mj_header endRefreshing];
        [self showNewStatus:statuses.count];
        
        NSMutableArray *statusArray = [NSMutableArray array];
        
        for (CZStatus *status in statuses) {
            LMStatusFrame *statusF = [[LMStatusFrame alloc] init];
            statusF.status = status;
            [statusArray addObject:statusF];
        }
    
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
        
        [self.statusFrames insertObjects:statusArray atIndexes:indexSet];
        [self.tableView reloadData];

        
    } failure:^(NSError *error) {
        
    }];
    
}


- (void)showdateUp
{
    
    
    NSString *max_idstr = nil;
    
    if (self.statusFrames.count) {
        
        
         CZStatus *s = [[self.statusFrames lastObject] status];
        
       long long maxId = [s.idstr longLongValue]-1 ;
        max_idstr = [NSString stringWithFormat:@"%lld",maxId];
        
    }
    
    
    [LMStatusTool oldStatusWithMaxId:max_idstr success:^(NSArray *statuses) {
        
        [self.tableView.mj_footer endRefreshing];
        
        NSMutableArray *statusArray = [NSMutableArray array];
        
        for (CZStatus *status in statuses) {
            LMStatusFrame *statusF = [[LMStatusFrame alloc] init];
            statusF.status = status;
            [statusArray addObject:statusF];
        }
        
         [self.statusFrames addObjectsFromArray:statusArray];
        
         [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        

    }];
    
    
}


- (void)showNewStatus:(int)count
{
    CGFloat x = 0;
    
    CGFloat w = self.view.width;
    CGFloat h = 35;
    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame)-h;
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(x, y, w, h)];
    
    lable.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    
    lable.text = [NSString stringWithFormat:@"最新微博的数%d",count];
    
    lable.textAlignment = NSTextAlignmentCenter;
    
    [self.navigationController.view insertSubview:lable belowSubview:self.navigationController.navigationBar];
    
    
    [UIView animateWithDuration:0.25 animations:^{
        lable.transform = CGAffineTransformMakeTranslation(0, h);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.25 delay:2 options:UIViewAnimationOptionCurveLinear animations:^{
            lable.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
        }];
    }];
    
    
}



- (void)titleClick:(UIButton *)button
{
    button.selected = !button.selected;
    
    LMCover *cover = [LMCover show];
    
    cover.delegate = self;
    
    CGFloat popW = 200;
    CGFloat popX = (self.view.width-200)*0.5;
    CGFloat popY = 55;
    CGFloat popH = popW;
    
    LMPopMenu *menu = [LMPopMenu showInRect:CGRectMake(popX, popY, popW, popH)];
    menu.contentView = self.one.view;
    
}

- (void)coverDidClickCover:(LMCover *)cover
{
    [LMPopMenu hide];
    
    _titleButton.selected = NO;
}

-(void)friendsearch
{
    NSLog(@"%s",__func__);
}

-(void)pop
{
   
    LMOneViewController *one = [[LMOneViewController alloc] init];
    
   
    one.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:one animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.statusFrames.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LMStatusCell *cell = [LMStatusCell cellWithTableView:tableView];
    
    LMStatusFrame *statusFrame = self.statusFrames[indexPath.row];
    
    cell.statusFrame = statusFrame;
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     LMStatusFrame *statusFrame = self.statusFrames[indexPath.row];
    
    NSLog(@"%d",statusFrame.cellheight);
    return statusFrame.cellheight;
}


@end
